from mqtt import connect_mqtt
import time
import urequests
from machine import Pin
from config import SEVER_URL
# 定义板载灯连接的 GPIO 引脚
led_pin = Pin(2, Pin.OUT)

def send_audio_data(chunks):
    all_data_sent = False
    batch_size = 20
    batch = []
    total_send_time = 0
    for chunk in chunks:
        led_pin.value(1)
        batch.append(chunk)
        if len(batch) == batch_size:
            data_to_send = b''.join(batch)
            start_send_time = time.ticks_ms()
            connect_mqtt(data_to_send)
            end_send_time = time.ticks_ms()
            batch_send_duration = end_send_time - start_send_time
            total_send_time += batch_send_duration
            batch = []
    all_data_sent = True
    total_send_time_seconds = total_send_time / 1000
    print(f"发送音频数据耗时: {total_send_time_seconds} 秒")
    return all_data_sent




def tcp_send_audio_data(chunks):
    all_data_sent = False
    batch_size = 20
    batch = []
    total_send_time = 0
    for chunk in chunks:
        led_pin.value(1)
        batch.append(chunk)
        if len(batch) == batch_size:
            data_to_send = b''.join(batch)
            start_send_time = time.ticks_ms()
            response = urequests.get(SEVER_URL+'/tcp', data=data_to_send)
            response.close()
            end_send_time = time.ticks_ms()
            batch_send_duration = end_send_time - start_send_time
            total_send_time += batch_send_duration
            batch = []
            print('tcp发送数据')
    all_data_sent = True
    total_send_time_seconds = total_send_time / 1000
    print(f"发送音频数据耗时: {total_send_time_seconds} 秒")
    return all_data_sent
